package com.sanno.user.util;



import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTutil {
    private static final String KEY = "abc!@#123";

    /**
     * 生成token
     * @param map //传入payload
     * @return 返回token
     */
    public static String getToken(Map<String, String> map){    //map中放用户信息
        JWTCreator.Builder builder = JWT.create();
        //设置Payload负荷（用户信息）
        map.forEach((k,v) -> {
            builder.withClaim(k, v);
        });
        //设置token有效期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 60*60*24*60);
        builder.withExpiresAt(instance.getTime());
        //产生token
        String token = builder.sign(Algorithm.HMAC256(KEY));
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);
    }

    /**
     * 获取token中的payload
     * @param token
     * @return
     */
    public static DecodedJWT getDecodedJWT(String token) {
        return JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);
    }
}
